<!DOCTYPE html>
<head>
    <title>实时数据</title>
    <meta charset="utf-8">
    <!-- 引入 ECharts 文件 -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@4/dist/echarts.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
</head>
<body>
<!-- 为ECharts准备一个具备大小（宽高）的Dom -->
<div id="main" style="width: 100%;height:500px;"></div>
<script type="text/javascript">
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('main'));

    option = {
        title: {
            text: '实时数据'
        },
        tooltip: {
            trigger: 'axis',
        },
        toolbox: {
            show: true,
            feature: {
                dataZoom: {
                    yAxisIndex: 'none'
                },
                dataView: {readOnly: false},
                magicType: {type: ['line', 'bar']},
                //restore: {},
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'time',
            boundaryGap: false, // ['5%', '5%']
            splitLine: {
                show: false
            }
        },
        yAxis: {
            type: 'value',
            boundaryGap: [0,'100%']
        },
        series:[
            {
                name: 'all',
                type: 'line',
            /*  markPoint: {
                    data: [
                        {type: 'max', name: '最大值'}//, {type: 'min', name: '最小值'}
                    ]
                },
                markLine: {
                    data: [
                        {type: 'average', name: '平均值'}
                    ]
                },*/
            showSymbol: false,
            hoverAnimation: false,
            data:[]
        }]
    };
    var realtimeData = {
        all: {
            time: '', ok: 0, fail: 0, ok_max: 0, ok_max_time: '', fail_max: 0, fail_max_time: ''
        }
    };
    var key = 'interface/*';
    var keyList = ['interface/admin','interface/api','interface/chain'];
    var show_status = 1; //1成功 0失败
    var series = [{data:[]}];
    var series_key = {};

    var show_num = 300;
    if(keyList){
        for(i in keyList){
            path = keyList[i];
            option.series.push({
                name: path,
                type: 'line',
                showSymbol: false,
                hoverAnimation: false,
                data:[]
            });
            series_key[path] = parseInt(i)+1;
            series.push({data:[]});
        }
    }

    function realtime(data) {
        data = JSON.parse(data);
        var d,okSum=0,failSum=0,pathOk=0,pathFail=0,name,name2;
        for (time in data){
            //console.log(i, data[i]);
            d = new Date(time*1000);
            name=d.toString();
            name2 =  [d.getFullYear(), d.getMonth() + 1, d.getDate()].join('/')+' '+d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();

            okSum=0;failSum=0;
            //console.log(name, okSum, failSum);
            for(path in data[time]){
                pathOk=0;pathFail=0;
                if(realtimeData[path]==undefined){
                    realtimeData[path] = {
                        ok: 0, fail: 0, ok_max: 0, ok_max_time: '', fail_max: 0, fail_max_time: ''
                    };
                }
                for(ip in data[time][path]){
                    pathOk += data[time][path][ip].ok;
                    pathFail += data[time][path][ip].fail;
                }
                okSum += pathOk;
                failSum += pathFail;

                if(realtimeData[path].ok_max<pathOk){
                    realtimeData[path].ok_max = pathOk;
                    realtimeData[path].ok_max_time = name2;
                }
                if(realtimeData[path].fail_max<pathFail){
                    realtimeData[path].fail_max = pathFail;
                    realtimeData[path].fail_max_time = name2;
                }
                realtimeData[path].ok = pathOk;
                realtimeData[path].fail = pathFail;

                if(series_key[path]!=undefined){
                    console.log(series_key[path]);
                    series[series_key[path]].data.push({
                        name: name,
                        value:[name2, show_status == 1 ? pathOk : pathFail]
                    });
                    if(series[series_key[path]].data.length>show_num) series[series_key[path]].data.shift();
                }
            }

            series[0].data.push({
                name: name,
                value:[name2, show_status == 1 ? okSum : failSum]
            });
            if(series[0].data.length>show_num) series[0].data.shift();
            //console.log(name, okSum, failSum);
            if(realtimeData.all.ok_max<okSum){
                realtimeData.all.ok_max = okSum;
                realtimeData.all.ok_max_time = name2;
            }
            if(realtimeData.all.fail_max<failSum){
                realtimeData.all.fail_max = failSum;
                realtimeData.all.fail_max_time = name2;
            }
            realtimeData.all.ok = okSum;
            realtimeData.all.time = name2;
            realtimeData.all.fail = failSum;
        }
        //console.log(series);
        myChart.setOption({
            series:series
        });
    }
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
</script>

<div id="output_realtime"></div>
<div id="output"></div>
<script language="javascript"type="text/javascript">
    var wsUri ="ws://{$ws_address}/";
    var output,output_realtime;

    function init() {
        output = document.getElementById("output");
        output_realtime = document.getElementById("output_realtime");
        runWebSocket();
    }

    function runWebSocket() {
        websocket = new WebSocket(wsUri);
        websocket.onopen = function(evt) {
            onOpen(evt)
        };
        websocket.onclose = function(evt) {
            onClose(evt)
        };
        websocket.onmessage = function(evt) {
            onMessage(evt)
        };
        websocket.onerror = function(evt) {
            onError(evt)
        };
    }

    function onOpen(evt) {
        writeToScreen("CONNECTED");
        if(websocket.readyState==1){
            doSend('{"cmd":"join_push_group", "key":"'+ key +'","sec":2}');
            //doSend('{"c":"login","data":{"username":"admin","password":"/pky9p84"}}');
        }
    }

    function onClose(evt) {
        writeToScreen("DISCONNECTED<div><a href='javascript:runWebSocket()'>重连</a></div>");
    }

    function onMessage(evt) {
        writeToScreen('<span style="color: blue;">RESPONSE: '+ evt.data+'</span>');
        evt.data!='ok' && realtime(evt.data);
    }

    function onError(evt) {
        console.log(evt)
        writeToScreen('<span style="color: red;">ERROR:</span> '+ evt.data);
    }

    function doSend(message) {
        writeToScreen("SENT: " + message);
        websocket.send(message);
    }

    function writeToScreen(message) {
        //output.innerHTML = message;return;
       /* var pre = document.createElement("p");
        pre.style.wordWrap = "break-word";
        pre.innerHTML = message;
        output.appendChild(pre);*/
        output.innerHTML = message;

        output_realtime.innerHTML = JSON.stringify(realtimeData);
    }

    init();
    //window.addEventListener("load", init, false);
</script>
</body>
</html>